﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UI.Lib;
using Components;
using UI.Lib.Factory;
using System.Collections;

namespace UI.SellOrder
{
    public partial class FrmBackMedit : UI.ParentForm.BaseMedit
    {
        public FrmBackMedit(string modulecode, string action, string text, string key)
            : base(modulecode, action)
        {
            InitializeComponent();

            this.Text = text;
            this.Key = key;

            //回写的方法
            this.SaveCallFuntion = "Ord4a00Manager$SaveData"; //保存的方法
            IsAfterSaveCloseWin = false;
            this.MaxStateFlag = true;
            this.allowDtlEmpty = false; //可能用户一次想把全部的记录删除
            if (!string.IsNullOrEmpty(this.Key))
            {
                LoadData();
                IsAfterSaveCloseWin = true;
            }
            if ("P" == action)
            {
                tspBtnAdd.Visible = false;
                tspBtnDel.Visible = false;
                this.saveDtlDataToServer = false;
            }

            if ("S" == action)
            {
                tspBtnAdd.Visible = false;
                tspBtnDel.Visible = false;

                this.dgvDtl.Focus(0, "accqty");
            }
        }

        protected override void PageInit()
        {
            //this.tbSummary.DefaultWidth = 150;
        }

        protected override bool BeforeDtlPopUp(string name, ref string where, ref string[] others)
        {
            if ("productcode" == name)
            {
                where = Context.GetAppKeyWhere("muser");
                //动态改变弹出框的表内容
                string table = string.Format(@"(
    select productcode, productname, isnull(lstsprice, bprice) as bprice, pamt, pct, listid, muser, spno, 
    lstsqty, lstsprice, lstsdate
from    
(
	SELECT a.productcode, a.productname, a.bprice, a.pamt, a.pct, a.listid, a.muser, b.spno,
	(SELECT TOP 1 pqty FROM Ord3a00 z INNER JOIN Ord3a01 x ON z.listid = x.plistid WHERE z.sellerid =  '{0}' AND z.splistid = '{1}' AND x.pdlistid = a.listid AND z.status > 2 ORDER BY bookdate DESC) AS lstsqty,
	(SELECT TOP 1 ordprice FROM Ord3a00 z INNER JOIN Ord3a01 x ON z.listid = x.plistid WHERE z.sellerid =  '{0}' AND z.splistid = '{1}' AND x.pdlistid = a.listid AND z.status > 2 ORDER BY bookdate DESC) AS lstsprice,
	(SELECT TOP 1 reqdate FROM Ord3a00 z INNER JOIN Ord3a01 x ON z.listid = x.plistid WHERE z.sellerid =  '{0}' AND z.splistid = '{1}' AND x.pdlistid = a.listid AND z.status > 2 ORDER BY bookdate DESC) AS lstsdate
	FROM Pot3a00 a
	LEFT JOIN Bas1a13 b ON a.listid = b.pid AND b.slistid = '{0}'
    WHERE a.status = '1'
    ) W 
) M
", Validation.ToString(this.tbSummary.GetValue("slistid"))
 , Validation.ToString(this.tbSummary.GetValue("splistid")));

                others = new string[] { table };
            }

            return true;
        }

        protected override void AfterCreateSummaryControl(string name, Control c)
        {
            //if ("comcode" == name)
            //{
            //    TextBox txt = c as TextBox;
            //    if (txt == null) return;
            //    //公司代码编辑框失去焦点时。查询是否可以退货
            //    txt.Leave += new EventHandler(txt_Leave);
            //}
        }

        void txt_Leave(object sender, EventArgs e)
        {
            string splistid = Validation.ToString(this.tbSummary.GetValue("splistid"));
            if (string.IsNullOrEmpty(splistid))
            {
                string sellerid = Validation.ToString(this.tbSummary.GetValue("slistid"));
                if (string.IsNullOrEmpty(sellerid)) //未能录入门店信息，不能查询是否可以退货
                {
                    MessageBox.Show("请先选择门店！", "提示");
                    this.tbSummary.Focus("shopcode");
                    this.tbSummary.SetValue("comcode", "");
                    return;
                }
            }

            string comcode = Validation.ToString(this.tbSummary.GetValue("comcode"));
            if (string.IsNullOrEmpty(comcode))
            {
                this.tbSummary.SetValue("backmk", "Y"); //默认允许退货
                return;
            }

            Hashtable tb = new Hashtable();
            tb["@comcode"] = comcode;
            tb["@shopid"] = splistid;
            tb["@sellerid"] = Validation.ToString(this.tbSummary.GetValue("slistid"));

            //得到该公司是否允许退货
            string mk = CommonHelper.Entity.ExecFunScalar("getbackmk", tb);
            if (!string.IsNullOrEmpty(mk))
            {
                this.tbSummary.SetValue("backmk", mk);
            }
        }

        public override bool BeforePopWin(string name, ref string where, ref string[] others)
        {
            if ("sellercode" == name) //销售商
            {
                where = string.Format("status ='1' {0}", Context.GetAppKeyWhere("usercode", true));
            }
            else if ("valuecode" == name) // 物流
            {
                where = Context.GetAppKeyWhere("usercode");
            }
            else if ("typecode" == name) //类别代码
            {
                where = Context.GetAppKeyWhere("muser");
            }
            else if ("shopcode" == name)//门店
            {
                string sellerid = Validation.ToString(this.tbSummary.GetValue("slistid"));
                if (string.IsNullOrEmpty(sellerid))
                {
                    MessageBox.Show("请先选择销售商！", "提示");
                    this.tbSummary.Focus("sellercode");
                    return false;
                }

                where = string.Format("slistid = '{0}' {1} ", sellerid, Context.GetAppKeyWhere("muser", true));
            }
            else if ("comcode" == name) //公司代码
            {
                string sellerid = Validation.ToString(this.tbSummary.GetValue("slistid"));
                if (string.IsNullOrEmpty(sellerid))
                {
                    MessageBox.Show("请先选择销售商！", "提示");
                    this.tbSummary.Focus("sellercode");
                    return false;
                }

                where = string.Format("slistid = '{0}' ", sellerid);
            }
            else if ("addcode" == name) //送货地址
            {
                string splistid = Validation.ToString(this.tbSummary.GetValue("splistid"));
                if (string.IsNullOrEmpty(splistid))
                {
                    MessageBox.Show("请先选择门店！", "提示");
                    this.tbSummary.Focus("shopcode");
                    return false;
                }

                where = string.Format("status = '01' AND slistid = '{0}' AND plistid = '{1}' ",
                    Validation.ToString(this.tbSummary.GetValue("slistid")), splistid);
            }
            else if ("stocode" == name) //仓库信息
            {
                where = string.Format("statuscode = '1' {0}",
                    Context.GetAppKeyWhere("usercode", true));
            }

            return true;
        }

        public override void AfterPopWin(string name, System.Collections.Hashtable data, bool ischange)
        {
            if (ischange)
            {
                if ("sellercode" == name)
                {
                    this.tbSummary.SetValue("splistid", "");
                    this.tbSummary.SetValue("shopcode", "");
                    this.tbSummary.SetValue("shopname", "");
                    this.tbSummary.SetValue("comcode", "");
                    this.tbSummary.SetValue("comname", "");
                    this.tbSummary.SetValue("tranday", "0");
                    this.tbSummary.SetValue("tlistid", "");
                    this.tbSummary.SetValue("addcode", "");
                    this.tbSummary.SetValue("addname", "");
                }
                else if ("shopcode" == name)
                {
                    this.tbSummary.SetValue("comcode", "");
                    this.tbSummary.SetValue("comname", "");
                    this.tbSummary.SetValue("tlistid", "");
                    this.tbSummary.SetValue("addcode", "");
                    this.tbSummary.SetValue("addname", "");
                }
            }
        }

        //加载修改数据
        private void LoadData()
        {
            base.LoadEditData(null, string.Format(" a.listid ='{0}' ", this.Key));
            base.LoadDtlData(null, string.Format(" a.plistid ='{0}' ", this.Key));
        }

        protected override void AfterGridEndEdit(string colName, DataGridViewCellEventArgs e)
        {
            if ("bqty" == colName || "price" == colName) //修改完预退数量、预退金额，计算总额
            {
                double price = Validation.ToDouble(this.dgvDtl.GetValue("price")); //价格
                double bqty = Validation.ToDouble(this.dgvDtl.GetValue("bqty")); //订货数量
                double all = price * bqty; //还要算上税率

                this.dgvDtl.SetValue("ordamt", all);
            }
            else if("accqty" == colName)
            {
                double price = Validation.ToDouble(this.dgvDtl.GetValue("price")); //价格
                double accqty = Validation.ToDouble(this.dgvDtl.GetValue(colName)); //实退数量
                double all = price * accqty;

                this.dgvDtl.SetValue("accamt", all.ToString("0.000"));
            }
        }

        protected override void AfterDtlValueChanged(string name, object value)
        {
            if ("ordamt" == name) //订单总额变化后更新概要的订单总额
            {
                this.tbSummary.SetValue("ordmat", CalcDtlAmt());
            }
        }

        private double CalcDtlAmt()
        {
            double sum = 0;
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                sum += Validation.ToDouble(dr.Cells["ordamt"].Value);
            }

            return sum;
        }

        protected override void AfterDelete()
        {
            this.tbSummary.SetValue("ordmat", CalcDtlAmt());
        }

        protected override bool Check()
        {
            if ("A" == this.Action || "M" == this.Action) //退单号 : 销售商 + 门店下退单号是否重复；
            {
                //门店
                string splistid = Validation.ToString(this.tbSummary.GetValue("splistid"));
                //销售商
                string sellerid = Validation.ToString(this.tbSummary.GetValue("slistid"));
                //退单号码
                string docno = Validation.ToString(this.tbSummary.GetValue("docno"));
                //单据主键
                string listid = Validation.ToString(this.tbSummary.GetValue("listid"));

                System.Collections.Hashtable hs = new System.Collections.Hashtable();
                hs["slistid"] = sellerid;
                hs["splistid"] = splistid;
                hs["docno"] = docno;

                //修改的时候将主键拼接进去
                if ("M" == this.Action) hs["%listid"] = string.Format("<>'{0}'", listid);

                bool reflt = UI.Lib.Factory.CommonHelper.Entity.DataInData("Ord4a00", hs);
                if (reflt)
                {
                    MessageBox.Show("该销售商的此门店已经存在退单号（" + docno + "）, 请重新录入！", "提示");
                    this.tbSummary.Focus("docno");
                    return false;
                }
            }

            return true;
        }
    }
}
